import jwt from 'jsonwebtoken'
const { verify } = jwt
import { sendErrorResponse, ResponseCode } from '../utils/response'

const jwtSecret = process.env.JWT_SECRET || 'your-secret-key'

interface JwtPayloadWithRole extends jwt.JwtPayload {
  role: string
}

const NO_AUTH_ROUTES: { path: string; method: string }[] = [
  { path: '/api/login', method: 'ANY' },
  { path: '/api/register', method: 'ANY' },
  { path: '/api/contactEmail', method: 'ANY' },
  { path: '/api/page-data', method: 'ANY' },
  { path: '/api/contact', method: 'ANY' },
  { path: '/api/about-us', method: 'ANY' },
  { path: '/api/upload', method: 'ANY' },
  { path: '/api/page-admin', method: 'GET' }, // 只放行 GET
  { path: '/api/auth/refresh', method: 'POST' }, // 添加刷新端点
  { path: '/api/uploader', method: 'POST' }, // 

]

export default defineEventHandler(async (event) => {
  // 2. 检查是否需要鉴权
  const reqPath = event.path
  const reqMethod = event.node.req.method
  // 判断是否在无需鉴权的接口和方法中
  if (
    NO_AUTH_ROUTES.some(
      route =>
        route.path === reqPath &&
        (route.method === reqMethod || route.method === 'ANY')
    )
  ) {
    return
  }

  if (!event.path?.startsWith('/api')) {
    return
  }
  // Skip auth routes
  if (event.path?.startsWith('/api/auth')) {
    return
  }



  // 2. 检查是否包含token
  const authHeader = getHeader(event, 'Authorization')
  const token = authHeader?.startsWith('Bearer ')
    ? authHeader.split(' ')[1]
    : authHeader || getCookie(event, 'auth_token')

  // console.log('Token:', token) // Debug

  if (!token) {
    // 对于API请求返回JSON错误
    if (event.path?.startsWith('/api')) {
      return sendErrorResponse(
        event,
        ResponseCode.UNAUTHORIZED,
        'Authentication required'
      )
    }
    // 对于页面请求重定向到登录页
    return sendRedirect(event, '/login')
  }

  try {
    const decoded = verify(token, jwtSecret) as JwtPayloadWithRole

    event.context.user = decoded

    // 3. 检查权限
    if (decoded?.role !== 'admin' && event.path?.startsWith('/api/admin')) {
      return sendErrorResponse(
        event,
        ResponseCode.FORBIDDEN,
        'Insufficient permissions'
      )
    }
  } catch (err) {
    console.error('JWT Verification Failed:', err) // 打印具体错误
    return sendErrorResponse(
      event,
      ResponseCode.UNAUTHORIZED,
      'Invalid or expired token'
    )
  }
})